var HOSTNAME="http://test.ngac.cn";
function formatDegree(value) {
	///<summary>将度转换成为度分秒</summary>  

	value = Math.abs(value);
	var v1 = Math.floor(value);//度  
	var v2 = Math.floor((value - v1) * 60);//分  
	var v3 = Math.round((value - v1) * 3600 % 60);//秒  
	return {
		"d" : v1,
		"f" : v2,
		"m" : v3
	};
};

function DegreeConvertBack(value) { ///<summary>度分秒转换成为度</summary>  
	var du = value.split("°")[0];
	var fen = value.split("°")[1].split("'")[0];
	var miao = value.split("°")[1].split("'")[1].split('"')[0];

	return Math.abs(du) + "."
			+ (Math.abs(fen) / 60 + Math.abs(miao) / 3600);
}

var DataType={
		"1":"嫦娥一号CCD03级",
		"2":"嫦娥二号CCD03",
		"3":"嫦娥一号激光高度计",
		"4":"LIOC",
		"5":"LOLA",
		"6":"全部类型"
}

//函数初始化
function init() {
	var userid = $.cookie("userid");
	if(userid=="" || userid==null || userid==undefined){
		$("#loginedname").text("游客");
		$("#alogin").text("请登录");
	}else{
		$("#loginedname").text($.cookie("username"));
		$("#alogin").text("已登录");
	}
	
	//login bt event
	$("#alogin").click(function(){
		$("#loginmodal").modal();
	});
	$("#btnpreregist").click(function(){
		$("#loginsection").toggle("normal");
		$("#registsection").toggle("normal");
		var v = $(this).val();
		if(v=="注册"){
			$(this).val("返回登录");
		}else{
			$(this).val("注册");
		}
	});
	
	$("#btnregist").click(function(){
		var username= $("#regusername").val();
		var pword = $("#regpassword").val();
		var repword = $("#regrepassword").val();
		if(pword!=repword){
			alert("两次密码不同，请重新输入");
			$("#regpassword").val("");
			$("#regrepassword").val("");
		}else if(username==""){
			alert("用户名不能为空！");
		}else if(pword==""){
			alert("密码不能为空！");
		}else{
			var user ={
					'name':username,
					'password':pword
			}
			userRegist(user);
		}
	});
	
	$("#btnlogin").click(function(){
		//$("#loginmodalcontainer").show();
		var username= $("#username").val();
		var pword = $("#password").val();
		if(username==""){
			alert("用户名不能为空！");
		}else if(pword==""){
			alert("密码不能为空！");
		}else{
			var user ={
					'name':username,
					'password':pword
			}
			userLogin(user);
		}
	});
	
	var mapOptions = {
		maxExtent : new OpenLayers.Bounds(-190, -90, 190, 90),
		maxResolution : 0.25,
		projection : "EPSG:4326"
	};
	//map = new OpenLayers.Map('map', mapOptions);
	

		
		
	//arcgis93rest
	//layer = new OpenLayers.Layer.ArcGIS93Rest("ArcGIS Server Layer", mapBaseURL);
	//map.addLayer(layer);
	//

	//map.addLayer(mylayer);引用外部系统测试用
	
	var mapOptions2 = { 
			resolutions: [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4],
			projection: new OpenLayers.Projection('EPSG:900999'),
			maxExtent: new OpenLayers.Bounds(-180.0,-90.0,180.0,90.0),
			units: "degrees",
			controls: []
			};
			map = new OpenLayers.Map('map', mapOptions2 );
			map.addControl(new OpenLayers.Control.PanZoomBar({
				position: new OpenLayers.Pixel(2, 15)
		}));
		map.addControl(new OpenLayers.Control.Navigation());
		map.addControl(new OpenLayers.Control.Scale($('scale')));
		map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
		var moonlayer = new OpenLayers.Layer.WMS(
		"moondata:CCDO3",HOSTNAME+"/geoserver/gwc/service/wms",
		{layers: 'moonzoon:ce103', format: 'image/jpeg' },
		{ tileSize: new OpenLayers.Size(256,256)});
		
		
		//map.zoomToExtent(new OpenLayers.Bounds(-179.99998338719456,-88.99996202392018,180.0,88.9999997100671));
		
		// setup tiled layer
        var poilabel = new OpenLayers.Layer.WMS(
                "moondata:allpoi - Tiled", HOSTNAME+"/geoserver/moondata/wms",
                {
                    "LAYERS": 'moondata:allpoi',
                    "STYLES": '',
                    format: 'image/jpeg',
					 transparent: true
                }
            );
    map.addLayers([moonlayer]);
	map.setCenter(new OpenLayers.LonLat(0, 0), 2);
	map.addControl(new OpenLayers.Control.OverviewMap());
	boxLayer = new OpenLayers.Layer.Vector("Box layer");
	map.addLayer(boxLayer);
	featureLayer = new OpenLayers.Layer.Vector("Feature layer");
	map.addLayer(featureLayer);
	
	featuremarkers = new OpenLayers.Layer.Markers( "Markers" );
	map.addLayer(featuremarkers);
	var mousePositionCtrl = new OpenLayers.Control.MousePosition({
	        formatOutput:function(lonLat){
	        	var lon = lonLat.lon.toFixed(3);
	        	var lat = lonLat.lat.toFixed(3);
				var result ="<span>x</span>"
				if(lon>180 || lon <-180 || lat<-90 || lat>90){
					result= "<span>x</span>";
				}else{
					result= "<span style='color:red;font-size:20px'>当前经度:"+lon+",纬度:"+lat+"</span>";
					}
				return result;
		    }
	});
	map.addControl(mousePositionCtrl);
	drawControls = new OpenLayers.Control.DrawFeature(boxLayer,
			OpenLayers.Handler.RegularPolygon, {
				handlerOptions : {
					sides : 4,
					irregular : true
				},
				featureAdded : function(eventArgs) {

					var bbox = eventArgs.geometry.getBounds();
					var xmin = formatDegree(bbox.left);
					$("#inputxmind").val(xmin.d);
					$("#inputxminf").val(xmin.f);
					$("#inputxminm").val(xmin.m);

					var xmax = formatDegree(bbox.right);
					$("#inputxmaxd").val(xmax.d);
					$("#inputxmaxf").val(xmax.f);
					$("#inputxmaxm").val(xmax.m);

					var ymin = formatDegree(bbox.bottom);
					$("#inputymind").val(ymin.d);
					$("#inputyminf").val(ymin.f);
					$("#inputyminm").val(ymin.m);

					var ymax = formatDegree(bbox.top);
					$("#inputymaxd").val(ymax.d);
					$("#inputymaxf").val(ymax.f);
					$("#inputymaxm").val(ymax.m);

					$("#inputxmin").val(bbox.left);
					$("#inputxmax").val(bbox.right);
					$("#inputymin").val(bbox.bottom);
					$("#inputymax").val(bbox.top);
					selectedpolygon = "POLYGON((" + bbox.left + " "
							+ bbox.bottom + "," + bbox.right + " "
							+ bbox.bottom + "," + bbox.right + " "
							+ bbox.top + "," + bbox.left + " "
							+ bbox.top + "," + bbox.left + " "
							+ bbox.bottom + "))";

					drawControls.deactivate();

				}

			});
	map.addControl(drawControls);
}

//regist user
function userRegist(userobj) {
	$.ajax({
		cache : false,
		type : "GET",
		data:userobj,
		url : "servlet/UserRegistAction",
		contentType : "application/json",
		success : function(msg) {
			if(msg.result){
				alert(msg.msg);
				$("#loginsection").toggle("normal");
				$("#registsection").toggle("normal");
			}else{
				alert(msg.msg);
			}
		},
		error : function(e) {
			alert("注册服务出问题，请联系管理员");
		}
	});
}

//regist user
function userLogin(userobj) {
	$.ajax({
		cache : false,
		type : "GET",
		data:userobj,
		url : "servlet/UserLoginAction",
		datatype:"json",
		contentType : "application/json",
		success : function(msg) {
			if(msg.result){
				
				$.cookie("username",userobj.name);
				$.cookie("userid",msg.userid);
				$("#loginedname").text(userobj.name);
				$("#alogin").text("已登录");
				$("#loginmodal").modal("hide");
			}else{
				alert(msg.msg);
			}
		},
		error : function(e) {
			alert("登录失败，请联系管理员");
		}
	});
}

//获取数据列表
function getDataList(seltype) {
	
	$.ajax({
		cache : false,
		type : "GET",
		data : {
			"bbox" : selectedpolygon,
			"type" : "6"//此处适配服务接口，记录用户下载的那种数据
		},
		url : "servlet/CheckDataWithBboxAction",
		contentType : "application/json",
		success : function(msg) {
			var size = msg.length;
			if (size > 0) {
				var trall = "";
				var downloadhead = "<form action='servlet/DownLoadDocAction' method='post'><input type='hidden' name='id' value='";
				var downloadtail ="<input type='submit' value='下载'/></form>";
				for ( var p in msg) {
	
					
					var feature = new OpenLayers.Feature.Vector(
							OpenLayers.Geometry
									.fromWKT(msg[p].geometry));
					featureLayer.addFeatures([ feature ]);
					var centerpoint = feature.geometry.getCentroid();//获取图形的中心点
					
					
					var d = downloadhead + msg[p].id+"'/>";
					d+="<input type='hidden' name='userid' value='"+$.cookie("userid")+"'/>";
					d+="<input type='hidden' name='type' value='"+seltype+"'/>";
					d+="<input type='hidden' name='name' value='"+msg[p].name+"'/>";
					d+= downloadtail;
					
					trall += "<tr><td poi='"+centerpoint.x+","+centerpoint.y+"'>"+(p+1)+"</td>"
					+"<td >" + msg[p].name+"</td>"
					+ "<td>" + DataType[msg[p].type]+"</td>"
					+"<td>"+msg[p].size+"M</td>"
					+ "<td>" + d + "</td></tr>";
					if(featuremarkers!=undefined){
						//map.removeLayer(featuremarkers);
						var markersArray = featuremarkers.markers;
							for(var i =0;i<markersArray.length;i++){
								featuremarkers.removeMarker(markersArray[i]);
							}
					}
					
					

		            var size = new OpenLayers.Size(21,25);
		            var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
		            var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
					var marker = new OpenLayers.Marker(new OpenLayers.LonLat(centerpoint.x,centerpoint.y),icon);
		            featuremarkers.addMarker(marker);
		            marker.events.register('mousedown', marker, function(evt) { alert(this.icon.url); OpenLayers.Event.stop(evt); });
				}
				$("#selectioncontainer").html(tabletemplate);
				$("#tbodyid").html(trall);
				//$('.footable').footable();
				
				$("#tbodyid tr").hover(function(){
					var poi = $($(this).find("td").get(0)).attr("poi").split(",");
					var centerpoint = new OpenLayers.LonLat(poi[0],poi[1]);
					map.panTo(centerpoint);
				});
				
				$("#btnback").click(function() {
					$("#selectioncontainer").html(
							selectioncontainer);
					$("#btnselectrectang").bind(
							"click", selectRec);
					$("#btnclear").click(function(){
						boxLayer.removeAllFeatures();
						featureLayer.removeAllFeatures();
						if(featuremarkers!=undefined){
							//map.removeLayer(featuremarkers);
							var markersArray = featuremarkers.markers;
							for(var i =0;i<markersArray.length;i++){
								featuremarkers.removeMarker(markersArray[i]);
							}
						}
					});
					
					$("#btnsearch").click(function() {
						var seltype = $("#seletionid option:selected").attr("value");
						search(seltype);

					});
				});
	
			} else {
	
				alert("此处无数据!");
			}
	
		},
		error : function(e) {
			alert("xxerror");
		}
	});
}

function selectRec() {
	boxLayer.removeAllFeatures();
	featureLayer.removeAllFeatures();
	drawControls.activate();


}

function search(type){
	//测试用 不用数据
	var userid = $.cookie("userid");
	if(userid=="" || userid==null || userid==undefined){
		$("#loginmodal").modal();
	}else{
		if(selectedpolygon==null ||selectedpolygon=="" || selectedpolygon==undefined){
			alert("请先选择或填入一个范围！");
		}else{
			getDataList(type);
		}
		
	}
	
	

}

